package com.hk.core.autoconfigure.authentication.security.servlet;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.hk.core.authentication.api.UserPrincipal;
import com.hk.core.autoconfigure.weixin.miniapp.WeiXinMiniappProperties;
import com.hk.weixin.security.miniapp.WeiXinMiniappAuthenticationFilter;
import com.hk.weixin.security.miniapp.WeiXinMiniappAuthenticationProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.function.Function;

/**
 * 微信小程序认证配置
 *
 * @author kevin
 * @date 2020年4月18日上午11:38:35
 */
@RequiredArgsConstructor
public class WeiXinMiniappAuthenticationSecurityConfigurer
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final WxMaService wxMaService;

    private final WeiXinMiniappProperties weiXinMiniappProperties;

    private final Function<WxMaJscode2SessionResult,UserPrincipal> authenticationFunction;

    /**
     * 此方法是将 WeiXinMiniappAuthenticationProvider 注册到spring security的filter 中
     */
    @Override
    public void configure(HttpSecurity http) {
        var filter = new WeiXinMiniappAuthenticationFilter(wxMaService, weiXinMiniappProperties.getLoginUrl());
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        var provider = new WeiXinMiniappAuthenticationProvider(authenticationFunction);
        http.authenticationProvider(provider).addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
